<template>
	<div class="ctfQuestion-warp">
	    <Row style="margin-bottom:10px">
        	<Col span="3">
        		<!--<Button type="primary" class="md-add-jh" @click="fileModal.show = true"></Button>-->
        	</Col>
    	</Row>
	    <Upload ref="upload"
            :action="uploadAction" 
            :show-upload-list="false" 
            :on-format-error="handleFormatError"
            :format="['jpg','jpeg','png','doc','docx','pdf','zip','rar']"
            :on-success="saveCtfFiles"
            :on-progress="getProgress"
            :headers="uploadHeader"
            :before-upload="handleUpload"
            footer-hide style="margin-bottom:10px">
          <Button icon="ios-cloud-upload-outline" type="primary" :disabled="fileList.length > 0 || (uploadList[0] && uploadList[0].status != 'finished')">上传题目附件</Button>
	    </Upload>
	    <div class="demo-upload-list" v-for="item in uploadList">
	    	<!--{{item}}-->
	        <template v-if="item.status === 'finished'">
	        </template>
	        <template v-else>
	        	<span style="margin-right:5px;">文件名：{{item.name}}</span> <span style="margin-right:5px;">文件大小：{{getFileSize(item.size)}}</span> <span style="margin-right:5px;">上传速度：{{speed}}</span>
	            <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
	        </template>
	    </div>
	    <p style="color:#ff9900"> <Icon type="ios-information-circle-outline" />仅允许上传一个文件，如有多个文件需上传，请压缩后上传</p>
	    <p style="color:#ff9900"> <Icon type="ios-information-circle-outline" />请上传doc,pdf,jpg,png,zip,rar等格式文件</p>
	    <!--，禁止上传*.exe|*.com|*.bat|*.vbs|等格式文件-->
	    <p style="color:#ff0000" v-if="showTip">文件格式错误</p>
	    <Table :show-header="false" :columns="fileCol" :data="fileList" v-show="fileList.length > 0"></Table>
	</div>
</template>
<script>
	import {createCtfFiles,delCtfFiles,queryCtfFiles,delfile} from '@/api/question'
  import encryption from '@/libs/encryption.js'
	export default {
		props:['chaId','show'],
		data(){
			let September = sessionStorage.getItem('November')
	    September = JSON.parse(encryption.SelfUseDecrypt(September))
			return{
				fileList:[],
				totalCount:0,
				fileModal:{
					show:false,
					loading:true,
					title:'添加File'
				},
				formValidate:{
					chaId: this.chaId
				},
				fileCol:[
//					{
//						type: 'index',
//						width: 60,
//						align: 'center',
//						ellipsis: true
//					},
					{
						title: 'File',
						key: 'fileName',
//						align: 'center',
//						ellipsis: true,
//						tooltip:true
					},
					{
					    title:'操作',
					    width:140,
					    render:(h,params) => {
					    	return h('div', [
								h('Button', {
									props: {
										type: 'primary',
										size: 'small'
									},
									style: {
										marginRight: '5px'
									}
								}, [
									h('a',{
			                    		attrs:{
			                    			href:"/api/minio/download/" + params.row.fileId,
			                    			download:''
			                    		},
			                    		style:{
			                    			color:'#fff'
			                    		}
			                    	},'下载')
								]),
								h('Poptip', {
									props: {
										confirm: true,
										'ok-text': "确定",
										'cancel-text': "取消",
										type: 'error',
										size: 'large',
										title: '你确定要删除吗?',
										transfer:true
									},
									style: {
										marginLeft: '0px'
									},
									on: {
										'on-ok': () => {
											this.delCtfFiles(params.row.fileId)
										}
									}
								}, [
									h('Button', {
										props: {
											type: 'error',
											size: 'small'
										},
										style: {
											marginRight: '5px'
										},
									}, '删除')
								])
							])
					    }
					}
				],
				uploadAction: "/api/minio/upload/permanent",
        uploadHeader: {
            Authorization:localStorage.token,
            Accept:'*/*'
        },
        fileBucket:'',
        showTip:false,
        speed:0,
        fileName:'',
        uploadList:[]
      }
		},
		computed:{

		},
		filters:{

		},
		watch:{
			'chaId':function(id){
				this.formValidate.chaId = id;
			},
			'show':function(show){
				if(show){
					this.showTip = false;
					this.queryCtfFiles();
				}
			}
		},
		methods:{
			queryCtfFiles(){
				queryCtfFiles(this.chaId).then(data => {
					if(data.code == 1){
						this.fileList = data.data.items || data.data;
						this.totalCount = data.data.totalCount;
					}else{
						this.$Message.warning(data.message);
					}
				})
			},
			delFile(id){
				return new Promise((resolve,reject) => {
					delfile(id).then(data => {
						if(data.code == 1){
							resolve()
						}else{
							resolve()
							this.$Message.warning(data.message);
						}
					}).catch(error => {
						this.$Message.warning(data.message);
					})
				})
			},
			delCtfFiles(id){
//				this.delFile(id).then(() => {
					delCtfFiles(id).then(data => {
						if(data.code == 1){
							this.$Message.info('操作成功');
							this.queryCtfFiles();
						}else{
							this.$Message.warning(data.message);
						}
					})
//				})
			},
			createCtfFiles(){
				createCtfFiles(this.formValidate).then(data => {
					if(data.code == 1){
						this.$Message.info('操作成功');
						this.queryCtfFiles();
						let boardCast = {
							chaId:this.chaId,
							op:"添加",
							type:"附件",
							name:this.fileName
						}
						this.$emit('addBoardCast', boardCast)
					}else{
						this.$Message.warning(data.message);
					}
				})
			},
			saveCtfFiles(file){
				this.uploadList = [];
				if(file.code == 1){
					this.formValidate.location = file.data;
					this.formValidate.fileName = file.info.originalName;
					this.formValidate.fileId = file.info.id;
					this.createCtfFiles();
				}else{
					this.$Message.warning(file.message);
				}
			},
//			getCtfFilesInfo(data){
//				this.formValidate = JSON.parse(JSON.stringify(data));
//			},
//			changePage(page){
//				this.queryCtfInfo.page = page;
//				this.queryCtfList();
//			},
//			changeSize(size){
//				this.queryCtfInfo.rows = size;
//				this.queryCtfList();
//			},
//			cancelLoading(name){
//		    	this[name].loading = false;
//		      	setTimeout(() => {
//		      		this[name].loading = true;
//		      	})
//		    },
//		    cancel(name){
//		  		this.$refs[name].resetFields();
//		  	},
		  	handleFormatError(sss){
		  		this.showTip = true;
		  	},
		  	handleUpload(file){
		  		this.uploadList = this.$refs.upload.fileList;
		  		// if((file.name || file.type).toLowerCase().indexOf("bat") != -1 || (file.name || file.type).toLowerCase().indexOf("exe") != -1 || 
		  		//    (file.name || file.type).toLowerCase().indexOf("com") != -1 || (file.name || file.type).toLowerCase().indexOf("vbs") != -1 ||
		  		//    (file.name || file.type).toLowerCase().indexOf("vbe") != -1 || (file.name || file.type).toLowerCase().indexOf("js") != -1 || 
		  		//    (file.name || file.type).toLowerCase().indexOf("jse") != -1 || (file.name || file.type).toLowerCase().indexOf("wsh") != -1 || 
		  		//    (file.name || file.type).toLowerCase().indexOf("wsf") != -1){
		  		//    	this.showTip = true;
		  		//     return false
		  		// }
		  		let exceededNum=file.name.lastIndexOf(".");
　　            let exceededStr=file.name.substring(exceededNum+1,file.name.length).trim().toLowerCase();
		  		let type = exceededStr;
		  		let imageArr = ['jpg','jpeg','png'];
		  		let docArr = ['doc','docx','pdf'];
		  		let otherArr = ['zip','rar'];
		  		if(imageArr.includes(type)){
		  			this.fileBucket = 'images';
		  			this.uploadAction = `/api/minio/upload/permanent?visibility=company&type=images&bucket=images`
		  		}else if(docArr.includes(type)){
					this.fileBucket = 'docs';
					this.uploadAction = `/api/minio/upload/permanent?visibility=company&type=docs&bucket=docs`
				}else if(otherArr.includes(type)){
					this.fileBucket = 'files';
					this.uploadAction = `/api/minio/upload/permanent?visibility=company&type=files&bucket=files`
				}else{
					this.showTip = true;
		  		    return false
				}
			 	this.fileName = file.name;
		  		this.showTip = false;
		  		let promise = new Promise((resolve)=>{
		            this.$nextTick(function () {
		                resolve(true)
		            })
		        });
		        return promise
		  	},
		  	getFileSize(size){
				let fileSize;
				if (size > 1024 * 1024) {
                    fileSize = (Math.round(size * 100 / (1024 * 1024)) / 100).toString() + 'MB'
                } else {
                    fileSize = (Math.round(size * 100 / 1024) / 100).toString() + 'KB'
                }
                return fileSize;
			},
			getProgress(progressEvent){
				var aaspeed = Number(progressEvent.loaded - this.loaded) || 0
                this.loaded = progressEvent.loaded
                if (aaspeed > 1024 * 1024) {
                    this.speed = (Math.round(aaspeed * 100 / (1024 * 1024)) / 100).toString() + 'MB/s'
                } else {
                    this.speed = (Math.round(aaspeed * 100 / 1024) / 100).toString() + 'KB/s'
                }
			},
		},
		mounted(){
//			this.uploadAction = `api/minio/upload/permanent?visibilty=share&type=${this.fileBucket}&bucket=${this.fileBucket}`
		},
		created(){

		}
	}
</script>
